package com.financing.wap.config;

/**
 * 
 */

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.financing.wap.service.payment.baofoo.model.BaofooConfig;
import com.financing.wap.util.WeChatGiftXMLUtil;

/**
 * 
 *
 */
public class ConfigurationLoaderUtil {
	
	final static Logger logger = LoggerFactory.getLogger(ConfigurationLoaderUtil.class.getClass());
	


	/**
	 * 把从数据库sysconfiguration表中加载到的参数转换为对应的配置对象
	 * @param conf
	 */
	public static void change2Beans() {
		//加载 宝付支付参数配置。
		ConfigurationLoaderUtil.loadBaofooConfig();
	}

	/**
	 * 加载宝付支付参数
	 * @param conf
	 */
	private static void loadBaofooConfig() {
		
		String paymentType = "baofoo" ;
		
		BaofooConfig baoFooConfig = BaofooConfig.getInstance();
		
		SAXReader  saxReader = new SAXReader();

		try {
			Document document = saxReader.read(WeChatGiftXMLUtil.class.getResourceAsStream("/PaymentConfig.xml"));
			Element rootElement=document.getRootElement();  

			
			for(@SuppressWarnings("unchecked") Iterator<Element> typeElementIterator = rootElement.elementIterator();typeElementIterator.hasNext();){

				Element valueElement = typeElementIterator.next();
				
				String id = valueElement.attributeValue("code");
				
				if(!paymentType.equals(id)){
					return ;
				}
				
				for(@SuppressWarnings("unchecked") Iterator<Element> valueElementIterator = valueElement.elementIterator();valueElementIterator.hasNext();){
					Element valuesElement = valueElementIterator.next();
					if("backTransRequest".equals(valuesElement.getName())){
						baoFooConfig.setBackTransRequest(valuesElement.getData().toString());
					}
					if("bindcardUrl".equals(valuesElement.getName())){
						baoFooConfig.setBindcardUrl(valuesElement.getData().toString());
					}
					if("cerPath".equals(valuesElement.getName())){
						baoFooConfig.setCerPath(valuesElement.getData().toString());
					}
					if("keyPath".equals(valuesElement.getName())){
						baoFooConfig.setKeyPath(valuesElement.getData().toString());
					}
					if("keyPwd".equals(valuesElement.getName())){
						baoFooConfig.setKeyPwd(valuesElement.getData().toString());
					}
					if("member_id".equals(valuesElement.getName())){
						baoFooConfig.setMember_id(valuesElement.getData().toString());
					}
					if("terminal_id".equals(valuesElement.getName())){
						baoFooConfig.setTerminal_id(valuesElement.getData().toString());
					}
					
				}
			}
			
		} catch (DocumentException e) {
			logger.error("Init allQuestionsList error :", e);
			throw new RuntimeException(e);
		}
		

		if( logger.isInfoEnabled()){
			logger.info( baoFooConfig.toString() ); 
		}
	}
}
